package com.dalongxin.work.page.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.recyclerview.BaseRecyclerAdapter;
import com.andview.refreshview.utils.LogUtils;
import com.dalongxin.work.BaseApplication;
import com.dalongxin.work.Constants;
import com.dalongxin.work.R;
import com.dalongxin.work.data.CloudDisk;
import com.dalongxin.work.data.CloudDiskDownloadItem;
import com.dalongxin.work.page.CloudDiskChooseFolderActivity;
import com.dalongxin.work.page.CloudDiskActivity;
import com.dalongxin.work.utils.HttpUtil;
import com.dalongxin.work.utils.OpenFiles;
import com.dalongxin.work.utils.StatusUtils;
import com.dalongxin.work.utils.ToastUtil;
import com.dalongxin.work.utils.Utils;
import com.dalongxin.work.view.LoadingDialog;
import com.dalongxin.work.view.MyCommonDialog;
import com.dalongxin.work.view.MyEditDialog;
import com.downloader.Error;
import com.downloader.OnCancelListener;
import com.downloader.OnDownloadListener;
import com.downloader.OnPauseListener;
import com.downloader.OnProgressListener;
import com.downloader.OnStartOrResumeListener;
import com.downloader.PRDownloader;
import com.downloader.Progress;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.x;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 云盘适配器
 * Created by zhaoyun on 16-9-1.
 */
public class CloudDiskAdapter extends BaseRecyclerAdapter<CloudDiskAdapter.DiskViewHolder> {

    private final static String TAG = "CloudDiskAdapter";
    private Context mContext;
    private LoadingDialog loadingDialog;
    private CloudDiskActivity cloudDiskActivity;
    private CloudDiskChooseFolderActivity mChooseFolderActivity;
    private List<CloudDisk> mDatas;
    private int mRole;
    private SharedPreferences sp;
    private boolean mIsEditing;
    private CheckBox mSelAllCb;

    private String mFileIds; //需要移动的文件，多个文件逗号隔开
    private String mFolderIds; //需要移动的文件夹，多个文件夹逗号隔开

    private Map<String, CloudDiskDownloadItem> mDownloadMap = new HashMap<>(); //下载文件的Map，点击下载就放入Map中

    public CloudDiskAdapter(Context context, List<CloudDisk> datas){
        mContext = context;
        mDatas = datas;
        sp = context.getSharedPreferences("clouddisk", Activity.MODE_PRIVATE);
    }

    public CloudDiskAdapter(Context context, List<CloudDisk> datas, CheckBox selAllCb){
        mContext = context;
        mDatas = datas;
        sp = context.getSharedPreferences("clouddisk", Activity.MODE_PRIVATE);
        mSelAllCb = selAllCb;
    }

    /**
     * 网盘首页创建Adapter用到，用来展示网盘列表
     */
    public CloudDiskAdapter(Context context, CloudDiskActivity fragment, int role, List<CloudDisk> datas, CheckBox selAllCb){
        mContext = context;
        cloudDiskActivity = fragment;
        this.mRole = role;
        mDatas = datas;
        sp = context.getSharedPreferences("clouddisk", Activity.MODE_PRIVATE);
        mSelAllCb = selAllCb;
    }

    /**
     * 目标文件夹页面创建Adapter用到，用来展示要移动的目标文件夹列表
     */
    public CloudDiskAdapter(Context context, CloudDiskChooseFolderActivity chooseFolderActivity, List<CloudDisk> datas){
        mContext = context;
        mChooseFolderActivity = chooseFolderActivity;
        this.mRole = 2;
        mDatas = datas;
        sp = context.getSharedPreferences("clouddisk", Activity.MODE_PRIVATE);
    }

    public void setFileIds(String fileIds) {
        mFileIds = fileIds;
    }

    public void setFolderIds(String folderIds) {
        mFolderIds = folderIds;
    }

    public void setEditing(boolean editing) {
        mIsEditing = editing;
    }

    public boolean isEditing() {
        return mIsEditing;
    }

    public void setDataAndNotify(List<CloudDisk> datas){
        mDatas = datas;
        notifyDataSetChanged();
    }

    public List<CloudDisk> getDatas() {
        return mDatas;
    }

    @Override
    public DiskViewHolder getViewHolder(View view) {
        return new DiskViewHolder(view, true);
    }

    @Override
    public DiskViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cloud_disk, parent, false);
        return new DiskViewHolder(v, true);
    }

    @Override
    public void onBindViewHolder(final DiskViewHolder holder, final int position, boolean isItem) {
        final CloudDisk item = mDatas.get(position);
        if (item.isFolder()) {
            holder.tvTitle.setText(item.getFileName());
            holder.tvSubTitle.setText(item.getFileCreatTime());
        } else {
            holder.tvTitle.setText(item.getFileName() /*+ "." + item.getFileFix()*/);
            double fileSize = 0;
            String unit = "";
            String pattern = "#.#";
            try{
                fileSize = Double.parseDouble(item.getFileSize());
                fileSize = fileSize / 1024 ;
                int newScale = 1;
                if(fileSize>=1024){//算到MB，就保留1位
                    fileSize = fileSize / 1024 ;
                    newScale = 1;
                    pattern = "0.0";
                    unit = "M";
                }else{//算到KB，就保留整数 （5.4.0版网盘KB也保留1位）
                    newScale = 1;
                    pattern = "0.0";
                    unit = "K";
                }
                BigDecimal b = new BigDecimal(fileSize);
                fileSize = b.setScale(newScale,BigDecimal.ROUND_HALF_UP).doubleValue();

            }catch (Exception e){
                fileSize=0;
                e.printStackTrace();
            }
            DecimalFormat df = new DecimalFormat(pattern);
            String fileSizeString = fileSize==0?"<1K":df.format(fileSize)+unit;
            holder.tvSubTitle.setText(fileSizeString + "    " + item.getFileCreatTime());
            String userId = BaseApplication.getInstance().getDefaultAccount()==null?"0": BaseApplication.getInstance().getDefaultAccount().getId()+"";
            String spKey1 = userId + "_" + item.getFileId() + "_status";
            String spKey2 = userId + "_" + item.getFileId() + "_current";
            String spKey3 = userId + "_" + item.getFileId() + "_total";
            int downloadStatus = sp.getInt(spKey1, 0);
            long current = sp.getLong(spKey2, 0);
            long total = sp.getLong(spKey3, 0);
            if(downloadStatus == CloudDisk.DOWNLOADING || downloadStatus == CloudDisk.PAUSING) {
                holder.downloadProgress.setVisibility(View.VISIBLE);
                holder.downloadProgress.setMax(100);
                holder.downloadProgress.setProgress((int)(current * 100 / total));
            }else if(downloadStatus == CloudDisk.FINISHED) {
                holder.downloadProgress.setVisibility(View.VISIBLE);
                holder.downloadProgress.setMax(100);
                holder.downloadProgress.setProgress(100);
            }else {
                holder.downloadProgress.setVisibility(View.GONE);
            }
        }
//        Glide.with(mContext).load(item.getFilePic()).into(holder.ivIcon);

        //设置文件icon
        if (item.isFolder()) {
            holder.ivIcon.setImageResource(R.mipmap.cloud_disk_folder);
        } else {
            String type = item.getFileType();
            if (!TextUtils.isEmpty(type)) {
                //0:图片 1:音频 2:视频 3:txt 4:pdf
                if (type.equals("0")) {
//                    holder.ivIcon.setImageResource(R.drawable.cloud_disk_pic_new);
                    x.image().bind(holder.ivIcon, item.getFilePic(),
                            BaseApplication.getInstance().getDefaultImageOption()
                                    .setFailureDrawableId(R.mipmap.cloud_disk_pic_new).build());
                } else if (type.equals("1")) {
                    holder.ivIcon.setImageResource(R.mipmap.cloud_disk_voice_new);
                } else if (type.equals("2")) {
                    x.image().bind(holder.ivIcon, item.getFilePic(),
                            BaseApplication.getInstance().getDefaultImageOption()
                                    .setFailureDrawableId(R.mipmap.cloud_disk_video_new).build());
                } else {
                    holder.ivIcon.setImageResource(R.mipmap.cloud_disk_txt_new);
                }
            }
        }

        if (mIsEditing) {
            holder.checkBox.setVisibility(View.VISIBLE);
            holder.rlMain.setVisibility(View.VISIBLE);
        } else {
            holder.checkBox.setVisibility(View.GONE);
            holder.rlMain.setVisibility(View.VISIBLE);
        }

        holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                item.setChecked(isChecked);
                if (!isChecked && mSelAllCb != null) {
                    mSelAllCb.setChecked(false);
                } else { //检查是否全选
                    for (CloudDisk cd : mDatas) {
                        if (!cd.isChecked()) {
                            return;
                        }
                    }
                    cloudDiskActivity.setSelAllBtnSelected();
                }
            }
        });
        holder.checkBox.setChecked(item.isChecked());

        holder.llOperate.setVisibility(View.GONE);
        holder.ivRightArrow.setSelected(false);

        if (item.isInTargetFolderList()) {
            holder.ivRightArrow.setVisibility(View.GONE);
        } else {
            if (mIsEditing) {
                holder.ivRightArrow.setVisibility(View.GONE);
            } else {
                holder.ivRightArrow.setVisibility(View.VISIBLE);
            }
        }

        final ImageView finalUnreadIv = holder.unreadIv;

        String userId = BaseApplication.getInstance().getDefaultAccount()==null?"0": BaseApplication.getInstance().getDefaultAccount().getId()+"";
        final String filePath = Utils.getSDPath() + Constants.FilePath + "/" + userId;
        String spKey1 = userId + "_" + item.getFileId() + "_status";
        String spKey2 = userId + "_" + item.getFileId() + "_current";
        String spKey3 = userId + "_" + item.getFileId() + "_total";
        String spKey4 = userId + "_" + item.getFileId() + "_downloadId";
        final int downloadStatus = sp.getInt(spKey1, 0);
        long current = sp.getLong(spKey2, 0);
        long total = sp.getLong(spKey3, 0);
        final int downloadId = sp.getInt(spKey4, 0);

        // 处理附件下载、预览事件监听
        View.OnClickListener attachmentClickListener = new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                CloudDiskDownloadItem dItem = mDownloadMap.get(item.getFileId());
                if(downloadStatus == CloudDisk.DOWNLOADING) {
                    ToastUtil.showShort("文件正在下载中，请稍候");
                }else if(downloadStatus == CloudDisk.PAUSING) {
                    if(downloadId != 0) {
                        PRDownloader.resume(downloadId);
                    }
                }else if(downloadStatus == CloudDisk.FINISHED) {
                    File destDir = new File(filePath);
                    if (!destDir.exists()) {
                        destDir.mkdirs();
                    }
                    File file = new File(destDir, item.getFileName());
                    if(file.exists()) {
                        OpenFiles.open(mContext, file);
                    }else {
                        if (dItem == null) {
                            dItem = new CloudDiskDownloadItem(item, holder.downloadProgress, v, holder.llPause);
                            mDownloadMap.put(item.getFileId(), dItem);
                        }
                        showDownloadDialog(filePath, item, dItem);
                    }
                }else {
                    if (dItem == null) {
                        dItem = new CloudDiskDownloadItem(item, holder.downloadProgress, v, holder.llPause);
                        mDownloadMap.put(item.getFileId(), dItem);
                    }
                    showDownloadDialog(filePath, item, dItem);
                }
            }
        };

        View.OnClickListener moreClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //更改未读为已读
                finalUnreadIv.setVisibility(View.GONE);
                ImageView imageView = (ImageView)((View)v.getParent()).findViewById(R.id.ivRightArrow);
                if (imageView.isSelected()) {
                    imageView.setSelected(false);
                    ((View) imageView.getParent().getParent()).findViewById(R.id.llOperate).setVisibility(View.GONE);
                } else {
                    imageView.setSelected(true);
                    ((View) imageView.getParent().getParent()).findViewById(R.id.llOperate).setVisibility(View.VISIBLE);

                    /*ListView listView = (ListView) parent;
                    if (position == getCount() - 1) { //如果是最后一项，展开更多操作时滚动到底，防止更多操作看不到
                        listView.setSelection(listView.getBottom());
                    }*/
                }
            }
        };

        if (item.isFolder()) { //如果是文件夹项，点击右箭头显示【更多操作】，点击其他部分进入该文件夹
            if (item.isInTargetFolderList()) { //如果是目标文件夹列表中的文件夹，点击图片进入该文件夹，点击其他部分表示移动到该文件夹
                holder.rlMain.setOnClickListener(new View.OnClickListener() { //移动到该文件夹
                    @Override
                    public void onClick(View v) {
                        moveToTargetFolder(item.getFileId());
                    }
                });
                holder.ivRightArrow.setOnClickListener(null);
                holder.ivIcon.setOnClickListener(new View.OnClickListener() { //进入文件夹
                    @Override
                    public void onClick(View v) {
                        mChooseFolderActivity.setCurrFolder(item.getFileId());
                        mChooseFolderActivity.getTargetFolderList();
                    }
                });
            } else {
                View.OnClickListener enterFolder = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) { //进入文件夹
                        if (cloudDiskActivity != null) { //网盘首页
                            cloudDiskActivity.setCurrFolder(item.getFileId());
                            cloudDiskActivity.setPage(1);
                            cloudDiskActivity.getCloudDiskList();
                        }
                        /*if (mSearchActivity != null) { //网盘搜索页
                            mSearchActivity.setCurrFolder(item.getFileId());
                            mSearchActivity.setPage(1);
                            mSearchActivity.setInFolder(true);
                            mSearchActivity.getCloudDiskSearchResultList();
                        }*/
                    }
                };
                holder.rlMain.setOnClickListener(enterFolder);
                //if ((item.getCreateId().equals(BaseApplication.getInstance().getDefaultAccount().getId())) && mRole != 2) {
                    holder.ivRightArrow.setOnClickListener(moreClickListener);
                    holder.ivIcon.setOnClickListener(moreClickListener);
                /*} else { //教师身份不是本人上传文件夹直接进入此文件夹下一级
                    holder.ivRightArrow.setOnClickListener(enterFolder);
                    holder.ivIcon.setOnClickListener(enterFolder);
                }*/
            }
        } else { //如果是文件项点击任何区域都显示【更多操作】
            holder.rlMain.setOnClickListener(attachmentClickListener);
            holder.ivRightArrow.setOnClickListener(moreClickListener);
            holder.ivIcon.setOnClickListener(attachmentClickListener);
        }

        if (mIsEditing) { //编辑状态下只能勾选
            View.OnClickListener onClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    holder.checkBox.setChecked(!item.isChecked());
                }
            };
            holder.rlMain.setOnClickListener(onClickListener);
            holder.ivRightArrow.setOnClickListener(onClickListener);
            holder.ivIcon.setOnClickListener(onClickListener);
        }

        // 网盘分享到班级圈功能5.3.0版本取消，为了避免android部分机型班级圈打开视频和语音不成功问题
        //5.4.0分享放开，分享只有微信朋友圈 微信好友和短信
        //分享到班级圈
        holder.llShare.setTag(0);
        holder.llShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int shareType=3,reType=0;
                //Common.requestShareChannel(mContext,item.getFilePic(),StringUtils.excludeNull(item.getFileName(),"这是一条来自和校园的分享"),item.getFileUrl(),item.getFileName()+"."+item.getFileFix(),"",shareType,reType, ClassContainActivity.PAGE_URL);
            }
        });

        //移动
        holder.llMove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int requestCode = CloudDiskChooseFolderActivity.MOVE_REQUEST_CODE;
                if (item.isFolder()) { //startActivityForResult为了移动完刷新列表
                    if (cloudDiskActivity != null) {
                        cloudDiskActivity.startActivityForResult(CloudDiskChooseFolderActivity.newIntent(mContext, "", item.getFileId()), requestCode);
                    }
                    /*if (mSearchActivity != null) {
                        mSearchActivity.startActivityForResult(CloudDiskChooseFolderActivity.newIntent(mContext, "", item.getFileId(), mClassId+"", true), requestCode);
                    }*/
                } else {
                    if (cloudDiskActivity != null) {
                        cloudDiskActivity.startActivityForResult(CloudDiskChooseFolderActivity.newIntent(mContext, item.getFileId(), ""), requestCode);
                    }
                    /*if (mSearchActivity != null) {
                        mSearchActivity.startActivityForResult(CloudDiskChooseFolderActivity.newIntent(mContext, item.getFileId(), "", mClassId + "", true), requestCode);
                    }*/
                }
            }
        });

        holder.llDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.isFolder()) {
                    showConfirmDialog("", item.getFileId(), position);
                } else {
                    showConfirmDialog(item.getFileId(), "", position);
                }
            }
        });
        holder.llRename.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showEditDialog(position, item.getFileId(), item.isFolder());
            }
        });

        //if((item.getCreateId().equals(BaseApplication.getInstance().getDefaultAccount().getId())) && mRole != 2){//如果是班主任或者是创建者则可以管理
            holder.llDelete.setVisibility(View.VISIBLE);
            holder.llRename.setVisibility(View.VISIBLE);
            //holder.llMove.setVisibility(View.VISIBLE);
            holder.llShare.setVisibility(View.GONE);
            holder.llMove.setVisibility(View.GONE);
        /*}else{
            holder.llDelete.setVisibility(View.GONE);
            holder.llRename.setVisibility(View.GONE);
            holder.llMove.setVisibility(View.GONE);
        }*/

        holder.llDownload.setTag(0);
        holder.llDownload.setOnClickListener(attachmentClickListener);
        holder.llPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CloudDiskDownloadItem dItem = mDownloadMap.get(item.getFileId());
                if (dItem != null) {
                    LogUtils.i(TAG + "文件id：" + item.getFileId() + " holder.pauseIv.setOnClickListener 暂停位置:" + dItem.getDownloadedBytes());
                    pauseDownload(item);
                }
            }
        });
        if(downloadStatus == CloudDisk.DOWNLOADING || downloadStatus == CloudDisk.PAUSING) {
            holder.downloadProgress.setVisibility(View.VISIBLE);
            holder.llDownload.setVisibility(View.GONE);
            holder.llPause.setVisibility(View.VISIBLE);
        }else if(downloadStatus == CloudDisk.FINISHED) {
            holder.downloadProgress.setVisibility(View.VISIBLE);
            holder.llDownload.setVisibility(View.GONE);
            holder.llPause.setVisibility(View.GONE);
        }else {
            holder.downloadProgress.setVisibility(View.GONE);
            holder.llDownload.setVisibility(View.VISIBLE);
            holder.llPause.setVisibility(View.GONE);
        }

        if (item.isFolder()) {
            holder.flDownload.setVisibility(View.GONE);
            holder.llShare.setVisibility(View.GONE);
        } else {
            holder.flDownload.setVisibility(View.VISIBLE);
            holder.llShare.setVisibility(View.GONE);
        }
    }

    @Override
    public int getAdapterItemCount() {
        return (mDatas==null)?0:mDatas.size();
    }

    public class DiskViewHolder extends RecyclerView.ViewHolder {
        CheckBox checkBox;
        ImageView ivIcon;
        TextView tvTitle;
        TextView tvSubTitle;
        ImageView ivRightArrow;
        LinearLayout llDownload,llPause,llDelete,llRename,llOperate,llShare,llMove;
        RelativeLayout rlMain;
        ImageView unreadIv;
        ProgressBar downloadProgress;
        View flDownload;
        public DiskViewHolder(View itemView, boolean isItem) {
            super(itemView);
            checkBox = (CheckBox) itemView.findViewById(R.id.item_checkbox);
            ivIcon = (ImageView) itemView.findViewById(R.id.ivIcon);
            tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
            tvSubTitle = (TextView) itemView.findViewById(R.id.tvSubTitle);
            ivRightArrow = (ImageView) itemView.findViewById(R.id.ivRightArrow);
            flDownload = itemView.findViewById(R.id.flDownload);
            llDownload = (LinearLayout) itemView.findViewById(R.id.llDownload);
            llPause = (LinearLayout) itemView.findViewById(R.id.llPause);
            llDelete = (LinearLayout) itemView.findViewById(R.id.llDelete);
            llRename = (LinearLayout) itemView.findViewById(R.id.llRename);
            llOperate = (LinearLayout) itemView.findViewById(R.id.llOperate);
            llShare = (LinearLayout) itemView.findViewById(R.id.llShare);
            llMove = (LinearLayout) itemView.findViewById(R.id.llMove);
            rlMain = (RelativeLayout)itemView.findViewById(R.id.rlMain);
            unreadIv = (ImageView) itemView.findViewById(R.id.unread_iv);
            downloadProgress = (ProgressBar) itemView.findViewById(R.id.progress_bar);
        }
    }

    private boolean checkIfAFileDownloading() {
        for (String fileId : mDownloadMap.keySet()) {
            CloudDiskDownloadItem dItem = mDownloadMap.get(fileId);
            if (dItem.getItem().getDownloadState() == CloudDisk.DOWNLOADING) {
                //如果有文件正在下载中，其他文件则无法下载
                Toast.makeText(mContext, "无法同时下载多个文件", Toast.LENGTH_SHORT).show();
                return true;
            }
        }
        return false;
    }

    private void moveToTargetFolder(String targetFolderId) {
        showLoading();
        HashMap<String, String> params = new HashMap<>();
        params.put("commandtype", "moveToTargetFolder");
        params.put("fileId", mFileIds);
        params.put("folderId", mFolderIds);
        params.put("targetFolderId", targetFolderId);
        LogUtils.i(TAG + " moveToTargetFolder 接口参数：\n" + params.toString());
        HttpUtil.getInstance().post(true, Constants.url_getCode, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtils.i(TAG + " moveToTargetFolder 接口返回：\n" + response.toString());
                if (response.optInt("ret") == 0) {
                    ToastUtil.showShort(mContext, response.optString("msg"));
                    mChooseFolderActivity.finishMoving();
                } else {
                    StatusUtils.handleStatus(response, mContext);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtil.showShort(mContext, "移动失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideLoading();
            }
        });
    }

    /**
     * adapter刷新列表时调用，否则item视图可能会串行
     */
    public void clearDownloadMap() {
        if (mDownloadMap != null) {
            mDownloadMap.clear();
        }
    }

    public void pauseDownload(CloudDisk item) {
        if (TextUtils.isEmpty(item.getFileId())) { //Adapter中调用的情况，不管哪一个正在下载，直接暂停
            for (String fId : mDownloadMap.keySet()) {
                CloudDiskDownloadItem dItem = mDownloadMap.get(fId);
                if (dItem.getItem().getDownloadState() == CloudDisk.DOWNLOADING) {
                    pauseHandle(dItem.getDownloadId(), dItem);
                }
            }
        } else {
            CloudDiskDownloadItem dItem = mDownloadMap.get(item.getFileId());
            if (dItem != null) {
                pauseHandle(dItem.getDownloadId(), dItem);
            }
        }
    }

    public void pauseAllDownload() {
        for (String fId : mDownloadMap.keySet()) {
            CloudDiskDownloadItem dItem = mDownloadMap.get(fId);
            if (dItem.getItem().getDownloadState() == CloudDisk.DOWNLOADING) {
                pauseHandle(dItem.getDownloadId(), dItem);
            }
        }
    }

    private void pauseHandle(int downloadId, CloudDiskDownloadItem dItem) {
        PRDownloader.pause(downloadId);
        LogUtils.i(TAG + " pauseDownload 暂停下载，暂停文件downloadId：" + downloadId + "，暂停位置：" + dItem.getDownloadedBytes());
        String userId = BaseApplication.getInstance().getDefaultAccount()==null?"0": BaseApplication.getInstance().getDefaultAccount().getId()+"";
        String spKey1 = userId + "_" + dItem.getItem().getFileId() + "_status";
        String spKey2 = userId + "_" + dItem.getItem().getFileId() + "_current";

        SharedPreferences.Editor edit = sp.edit();
        edit.putLong(spKey1, CloudDisk.PAUSING);
        edit.putLong(spKey2, dItem.getDownloadedBytes()); //记录中断下载时的位置
        edit.apply();

        dItem.getItem().setDownloadState(CloudDisk.PAUSING);
        dItem.getDownloadView().setVisibility(View.VISIBLE);
        dItem.getPauseView().setVisibility(View.GONE);
    }

    private MyEditDialog editDialog;
    private void showEditDialog(final int position, final String fileId, final boolean isFolder){
        final String oldName = mDatas.get(position).getFileName();
        int renameLength;
        if (isFolder) {
            renameLength = 12;
        } else {
            renameLength = 20;
        }
        editDialog = new MyEditDialog(mContext, renameLength, "文件重命名", oldName, "取消", "确定");
        editDialog.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editDialog.dismiss();
                hideSoftKeyBoard(editDialog.getEditView());
            }
        });
        editDialog.setOkListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newName = editDialog.getEditView().getText()
                        .toString().trim();
                if (TextUtils.isEmpty(newName)) {
                    ToastUtil.showShort(mContext, "请输入文件名");
                } else if (newName.equals(oldName)) {
                    editDialog.dismiss();
                    hideSoftKeyBoard(editDialog.getEditView());
                } else {
                    editDialog.dismiss();
                    hideSoftKeyBoard(editDialog.getEditView());
                    rClasenamesroomNetDiskFile(fileId, newName, isFolder, position);
                }
            }
        });
        editDialog.show();
    }

    /**
     * 隐藏软键盘
     */
    private void hideSoftKeyBoard(View view) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private void showDownloadDialog(final String fullPath, final CloudDisk item, final CloudDiskDownloadItem dItem){
        commonDialog = new MyCommonDialog(mContext, "提示消息", "是否开始下载？", "取消", "确认");
        commonDialog.setOkListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog.isShowing())
                    commonDialog.dismiss();
                String fileUrl = item.getFileUrl();
                String fileName = item.getFileName();
                /*//新版网盘断点下载
                OkHttpDownload okHttpDownload = new OkHttpDownload(fileId, fileUrl, fullPath, 0, CloudDiskAdapter.this);
                mDownloadMap.get(fileId).setOkHttpDownload(okHttpDownload);
                okHttpDownload.download(0);
                downloadingViewDisplay(dItem, 0);*/
                int downloadId = download(dItem, fileUrl, fullPath, fileName);
                dItem.setDownloadId(downloadId);
                String userId = BaseApplication.getInstance().getDefaultAccount()==null?"0": BaseApplication.getInstance().getDefaultAccount().getId()+"";
                String spKey1 = userId + "_" + item.getFileId() + "_status";
                String spKey2 = userId + "_" + item.getFileId() + "_current";
                String spKey3 = userId + "_" + item.getFileId() + "_total";
                String spKey4 = userId + "_" + item.getFileId() + "_downloadId";
                SharedPreferences.Editor edit = sp.edit();
                edit.putInt(spKey1, CloudDisk.DOWNLOADING);
                edit.putLong(spKey2, 0);
                edit.putInt(spKey4, downloadId);
                edit.apply();
            }
        });
        commonDialog.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog.isShowing()) {
                    commonDialog.dismiss();
                }
            }
        });
        commonDialog.show();
    }

    private void downloadingViewDisplay(CloudDiskDownloadItem dItem, long startPoint) {
        dItem.getProgressBar().setMax(Integer.parseInt(dItem.getItem().getFileSize()) / 1024);
        dItem.getProgressBar().setProgress((int) (startPoint / 1024));
        dItem.getProgressBar().setVisibility(View.VISIBLE);
        dItem.getDownloadView().setVisibility(View.GONE);
        dItem.getPauseView().setVisibility(View.VISIBLE);
        dItem.getItem().setDownloadState(CloudDisk.DOWNLOADING);
    }

    public int download(final CloudDiskDownloadItem dItem, String url, String dirPath, String fileName) {
        LogUtil.e("--download--url" + url);
        LogUtil.e("--download--dirPath" + dirPath);
        LogUtil.e("--download--fileName" + fileName);
        final File file = new File(dirPath, fileName);
        final int downloadId = PRDownloader.download(url, dirPath, fileName).build()
                .setOnStartOrResumeListener(new OnStartOrResumeListener() {
                    @Override
                    public void onStartOrResume() {

                    }
                })
                .setOnPauseListener(new OnPauseListener() {
                    @Override
                    public void onPause() {

                    }
                })
                .setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel() {

                    }
                })
                .setOnProgressListener(new OnProgressListener() {
                    @Override
                    public void onProgress(Progress progress) {
                        int pg = (int)(progress.currentBytes * 100f/progress.totalBytes);
                        dItem.getProgressBar().setMax(100);
                        dItem.getProgressBar().setProgress(pg);
                        dItem.getProgressBar().setVisibility(View.VISIBLE);
                        dItem.getDownloadView().setVisibility(View.GONE);
                        dItem.getPauseView().setVisibility(View.VISIBLE);
                        dItem.getItem().setDownloadState(CloudDisk.DOWNLOADING);

                        String userId = BaseApplication.getInstance().getDefaultAccount()==null?"0": BaseApplication.getInstance().getDefaultAccount().getId()+"";
                        String spKey2 = userId + "_" + dItem.getItem().getFileId() + "_current";
                        String spKey3 = userId + "_" + dItem.getItem().getFileId() + "_total";
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putLong(spKey2, progress.currentBytes);
                        edit.putLong(spKey3, progress.totalBytes);
                        edit.apply();
                    }
                })
                .start(new OnDownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                        dItem.getItem().setDownloadState(CloudDisk.FINISHED);
                        ((Activity) mContext).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (dItem != null && dItem.getItem().getDownloadState() == CloudDisk.FINISHED) {
                                    Toast.makeText(mContext, "下载完成", Toast.LENGTH_SHORT).show();
                                    String userId = BaseApplication.getInstance().getDefaultAccount()==null?"0": BaseApplication.getInstance().getDefaultAccount().getId()+"";
                                    String spKey1 = userId + "_" + dItem.getItem().getFileId() + "_status";
                                    String spKey2 = userId + "_" + dItem.getItem().getFileId() + "_current";
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putInt(spKey1, CloudDisk.FINISHED);
                                    edit.putLong(spKey2, dItem.getDownloadedBytes());
                                    edit.apply();
                                }
                                downloadResponse(dItem.getItem().getFileId(), file);
                            }
                        });
                    }

                    @Override
                    public void onError(Error error) {

                    }
                });
        return downloadId;
    }

    private MyCommonDialog commonDialog;
    private void showConfirmDialog(final String fileId, final String folderId, final int position){
        commonDialog = new MyCommonDialog(mContext, "提示消息", "确认删除吗？", "取消", "确认");
        commonDialog.setOkListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog.isShowing())
                    commonDialog.dismiss();
                List<Integer> positionList = new ArrayList<>();
                positionList.add(position);
                deleteClassroomNetDiskFile(fileId, folderId, positionList, false);
            }
        });
        commonDialog.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog.isShowing())
                    commonDialog.dismiss();
            }
        });
        commonDialog.show();
    }

    public void deleteClassroomNetDiskFile(String fileIds, String folderIds, final List<Integer> positions, final boolean isBatch) {
        showLoading();
        HashMap<String, String> params = new HashMap<>();
        if(fileIds == null || "".equals(fileIds)) {
            params.put("folderId", folderIds);
            HttpUtil.getInstance().post(true, Constants.url_delFolder, params, new Callback.CommonCallback<JSONObject>() {
                @Override
                public void onSuccess(JSONObject response) {
                    LogUtils.i(TAG + " url_delFolder 接口返回：\n" + response.toString());
                    if (response.optInt("ret") == 0) {
                        try {
                            if (cloudDiskActivity != null) { //网盘首页
                                cloudDiskActivity.getCloudDiskList();
                            }
                            /*if (mSearchActivity != null) { //网盘搜索页
                                mSearchActivity.getCloudDiskSearchResultList();
                            }*/
                            if (!isBatch) {
                                searchActivitySetResultAfterEditing(); //搜索页删除以后退回到网盘首页时刷新
                            }
                            ToastUtil.showShort(mContext, "已删除");
                            clearDownloadMap();
                        } catch (Exception ex) {
                            LogUtils.e(ex.getMessage());
                        }
                    } else {
                        StatusUtils.handleStatus(response, mContext);
                        ToastUtil.showShort(mContext, "删除失败");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ToastUtil.showShort(mContext, "删除失败");
                }

                @Override
                public void onCancelled(CancelledException cex) {
                }

                @Override
                public void onFinished() {
                    hideLoading();
                }
            });
        }else {
            params.put("fileIds", fileIds);
            LogUtils.i(TAG + " url_delFile 接口参数：\n" + params.toString());
            HttpUtil.getInstance().post(true, Constants.url_delFile, params, new Callback.CommonCallback<JSONObject>() {
                @Override
                public void onSuccess(JSONObject response) {
                    LogUtils.i(TAG + " deleteClassroomNetDiskFile 接口返回：\n" + response.toString());
                    if (response.optInt("ret") == 0) {
                        try {
                            if (cloudDiskActivity != null) { //网盘首页
                                cloudDiskActivity.getCloudDiskList();
                            }
                            /*if (mSearchActivity != null) { //网盘搜索页
                                mSearchActivity.getCloudDiskSearchResultList();
                            }*/
                            if (!isBatch) {
                                searchActivitySetResultAfterEditing(); //搜索页删除以后退回到网盘首页时刷新
                            }
                            ToastUtil.showShort(mContext, "已删除");
                            clearDownloadMap();
                        } catch (Exception ex) {
                            LogUtils.e(ex.getMessage());
                        }
                    } else {
                        StatusUtils.handleStatus(response, mContext);
                        ToastUtil.showShort(mContext, "删除失败");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ToastUtil.showShort(mContext, "删除失败");
                }

                @Override
                public void onCancelled(CancelledException cex) {
                }

                @Override
                public void onFinished() {
                    hideLoading();
                }
            });
        }
    }

    private void searchActivitySetResultAfterEditing() {
        /*if (mSearchActivity != null) {
            mSearchActivity.setResult(CloudDiskSearchActivity.RESULT_SEARCH);
        }*/
    }

    private void rClasenamesroomNetDiskFile(String fileId, final String name, boolean isFolder, final int position) {
        showLoading();
        HashMap<String, String> params = new HashMap<>();

        if(isFolder) {
            params.put("folderId", fileId);
            params.put("folderName", name);
            //params.put("fileType", fileType);
            LogUtils.i(TAG + " url_renameFile 接口参数：\n" + params.toString());
            HttpUtil.getInstance().post(true, Constants.url_renameFolder, params, new Callback.CommonCallback<JSONObject>() {
                @Override
                public void onSuccess(JSONObject response) {
                    LogUtils.i(TAG + " rClasenamesroomNetDiskFile 接口返回：\n" + response.toString());
                    if (response.optInt("ret") == 0) {
                        try {
                            mDatas.get(position).setFileName(name);
                            notifyDataSetChanged();
                            searchActivitySetResultAfterEditing();
                        } catch (Exception ex) {
                            LogUtils.e(ex.getMessage());
                        }
                    } else {
                        StatusUtils.handleStatus(response, mContext);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ToastUtil.showShort(mContext, "删除失败");
                }

                @Override
                public void onCancelled(CancelledException cex) {
                }

                @Override
                public void onFinished() {
                    hideLoading();
                }
            });
        }else {
            params.put("fileId", fileId);
            params.put("fileName", name);
            //params.put("fileType", fileType);
            LogUtils.i(TAG + " url_renameFile 接口参数：\n" + params.toString());
            HttpUtil.getInstance().post(true, Constants.url_renameFile, params, new Callback.CommonCallback<JSONObject>() {
                @Override
                public void onSuccess(JSONObject response) {
                    LogUtils.i(TAG + " rClasenamesroomNetDiskFile 接口返回：\n" + response.toString());
                    if (response.optInt("ret") == 0) {
                        try {
                            mDatas.get(position).setFileName(name);
                            notifyDataSetChanged();
                            searchActivitySetResultAfterEditing();
                        } catch (Exception ex) {
                            LogUtils.e(ex.getMessage());
                        }
                    } else {
                        StatusUtils.handleStatus(response, mContext);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ToastUtil.showShort(mContext, "删除失败");
                }

                @Override
                public void onCancelled(CancelledException cex) {
                }

                @Override
                public void onFinished() {
                    hideLoading();
                }
            });
        }
    }

    private void downloadResponse(String fileId, File file) {
        CloudDiskDownloadItem dItem = mDownloadMap.get(fileId);
        if (dItem != null) {
            if (dItem.getItem().getDownloadState() == CloudDisk.FINISHED) {
                dItem.getProgressBar().setVisibility(View.GONE);
            }
            dItem.getDownloadView().setVisibility(View.VISIBLE);
            dItem.getPauseView().setVisibility(View.GONE);
            // 下载成功后再次触发点击事件，直接打开已下载完成的附件
            //dItem.getDownloadView().performClick();
            OpenFiles.open(mContext, file);
        }
    }

    public void updateView(LinearLayoutManager layoutManager, long downId) {
        int visiblePosition = layoutManager.findFirstVisibleItemPosition();
        int itemIndex = -1;
        String userId = BaseApplication.getInstance().getDefaultAccount() == null ? "0" : BaseApplication.getInstance().getDefaultAccount().getId() + "";
        for (int i = 0; i < mDatas.size(); i++) {
            String key = userId + mDatas.get(i).getFileId();
            long downId2 = sp.getLong(key, 0);
            if (downId2 == downId) {
                itemIndex = i + 1;
                break;
            }
        }
    }

    protected void showLoading() {
        if(loadingDialog == null) {
            loadingDialog = new LoadingDialog(mContext, R.style.LoadingDialog);
        }
        loadingDialog.show();
    }

    protected void hideLoading() {
        if(loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

}
